package com.xjy.rpc.netty.handler;

import com.xjy.rpc.netty.client.Client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ReconnectHandler extends ChannelInboundHandlerAdapter {

    private Client client;

    public ReconnectHandler(Client client){
        this.client = client;
    }

    /** 
     * @description: channel 处于不活跃状态的调用 
     * @param: ctx 
     * @return: void
     * @author XJY
     * @date: 2024/10/17 10:48
     */ 
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("服务中断");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.execute(()-> client.connect());
    }

    /**
     * @description:  处理异常的方法，关闭管道
     * @param: ctx cause
     * @return: void
     * @author XJY
     * @date: 2024/10/17 10:44
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
